"use client";

import React, { useEffect, useState } from "react";
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  userControllerGetUserList,
  userControllerCreateUser,
  userControllerUpdateUser,
  userControllerDeleteUser,
} from "@/app/servers/api/user";

export default function UserManagePage() {
  const [users, setUsers] = useState<API.User[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingUser, setEditingUser] = useState<API.User | null>(null);

  const fetchUsers = async () => {
    try {
      const { data } = await userControllerGetUserList();
      setUsers(data);
    } catch {
      message.error("获取用户列表失败");
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);


  const handleEdit = (record: API.User) => {
    setEditingUser(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await userControllerDeleteUser({ id: id.toString() });
      message.success("删除成功");
      fetchUsers();
    } catch {
      message.error("删除失败");
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingUser) {
        await userControllerUpdateUser({
          id: editingUser.id,
          ...values,
        });
        message.success("更新成功");
      } else {
        await userControllerCreateUser(values);
        message.success("创建成功");
      }
      setIsModalVisible(false);
      fetchUsers();
    } catch {
      message.error(editingUser ? "更新失败" : "创建失败");
    }
  };

  const columns: ColumnsType<API.User> = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="mb-4">
      </div>

      <Table columns={columns} dataSource={users} rowKey="id" />

      <Modal
        title={editingUser ? "编辑用户" : "添加用户"}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: "请输入角色" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
